#!/bin/sh

BINPATH="/conf/sbin"
CONFPATH="/conf/.config"

if [ -s $CONFPATH/tweakpack.conf ]; then
    . $CONFPATH/tweakpack.conf
fi


[ -s $CONFPATH/web2wget.conf ] || exit 1
. $CONFPATH/web2wget.conf

[ -e $QFILE ] || touch $QFILE
[ -d $WDIR ] || mkdir -p $WDIR
[ -d $DDIR ] || mkdir -p $DDIR

#if wget is run then exit
ISRUN=`ps -w | grep -v grep | grep -c $WGET`
[ $ISRUN -gt 0 ] && exit 0
LASTGET1=`head -n 1 $QFILE | awk -F"|" '{print $1}'`
LASTGET2=`head -n 1 $QFILE | awk -F"|" '{print $2}'`
if [ -e $WDIR/$LASTGET1.log ]; then
  FINISH=`cat $WDIR/$LASTGET1.log | grep -c "100%"`
else
  FINISH=0
fi


if [ $FINISH -ge 1 ]; then
  tail -n +2 -q $QFILE > $WDIR/qfile
  mv -f $WDIR/qfile $QFILE
  chmod 666 $QFILE
  rm -f $WDIR/$LASTGET1.log
  rm -f $WDIR/$LASTGET1.err
  LASTGET1=`head -n 1 $QFILE | awk -F"|" '{print $1}'`
  LASTGET2=`head -n 1 $QFILE | awk -F"|" '{print $2}'`
else
  [ -s $WDIR/$LASTGET1.err ] && RETR=`cat $WDIR/$LASTGET1.err` || RETR=0
  if [ $RETR -gt $MAXRETR ]; then
    tail -n +2 -q $QFILE > $WDIR/qfile
    mv -f $WDIR/qfile $QFILE
    chmod 666 $QFILE
    rm -f $WDIR/$LASTGET1.log
    rm -f $WDIR/$LASTGET1.err
    LASTGET1=`head -n 1 $QFILE | awk -F"|" '{print $1}'`
    LASTGET2=`head -n 1 $QFILE | awk -F"|" '{print $2}'`
  else
    RETR=$((RETR+1))
    echo -n "$RETR" > $WDIR/$LASTGET1.err
  fi
fi

L=${#LASTGET1}
[ $L -gt 0 ] && nice -n 10 $WGET -c -b -nd -np -nH --passive-ftp -P $DDIR $SLIMIT -o $WDIR/$LASTGET1.log "$LASTGET2" > /dev/null

